package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public TravelComment save(TravelComment comment) {
        if (comment.getId() == null || "".equals(comment.getId().trim())){
            comment.setCreateTime(new Date());
        }
        String refId = comment.getRefComment().getId();
        if(refId != null && !"".equals(refId.trim())){
            TravelComment refComment = repository.findById(refId).get();
            comment.setRefComment(refComment);
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        // 拼接条件
        Query query = new Query();
        if (qo.getTravelId() != -1l){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        // 查询总条数
        long count = mongoTemplate.count(query, TravelComment.class);
        // 如果总条数为0，返回空集合
        if (count == 0){
            return Page.empty();
        }
        // 查询分页的结果集
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"createTime");
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl(list,pageable,count);
    }

    @Override
    public Long getCount(Long travelId) {
        Query query = new Query();
        if (travelId != -1l){
            query.addCriteria(Criteria.where("travelId").is(travelId));
        }
        long count = mongoTemplate.count(query, TravelComment.class);
        return count;
    }

}
